# -*-coding:utf-8 -*-
import time
from datetime import datetime, timedelta, timezone

from pymongo import MongoClient

from .. import config
from .base import XZBaseHandler


class GPSMongoHandler(XZBaseHandler):

    def __init__(self, *args, **kwargs):
        self.connect = MongoClient(config.MONGO['URL'])
        self.db = self.connect.get_database(config.MONGO['DB'])
        self.time_range = {
        }
        super().__init__(*args, **kwargs)

    def _ensure_index(self, collection):
        """根据localTime来创建时间"""
        self.db[collection].create_index('device_imei')
        self.db[collection].create_index('start_timespan')
        self.db[collection].create_index('vehicle_license_number')

    def _get_collection_name(self, dt: datetime):
        """生成集合的名字"""
        collection_name = dt.strftime("%Y%m")
        if collection_name not in self.db.list_collection_names():
            self.db.create_collection(collection_name)
            self._ensure_index(collection_name)
        return collection_name

    def _get_start_timespan(self, dt):
        minute = dt.minute // 5 * 5
        return datetime(
            year=dt.year,
            month=dt.month,
            day=dt.day,
            hour=dt.hour,
            minute=minute,
        )

    def handle(self, data):
        if data["vehicleId"] not in self.vin2vehicle_map:
            self.logger.warning(f'old_vehicle_id={data["vehicleId"]}')
            return
        vehicle_info = self.vin2vehicle_map[data['vehicleId']]
        if vehicle_info['imei'] in ['861290030047992']:
            return

        appLocations = data['appLocations']
        start_timespan = datetime.strptime(appLocations[0]['locationTime'], "%Y-%m-%d %H:%M:%S")
        start_time = self._get_start_timespan(start_timespan)
        set_on_insert = {
            'start_timespan': start_time,
            'device_imei': vehicle_info['imei'],
            "vehicle_license_number": vehicle_info['license_number'],
            "meta": {
                "version": 0.1,
                "provider": "xiao-zhuo"
            },
            'created_time': datetime.now(),
        }

        gps_points = []
        cnt = 0
        for row in appLocations:
            gps_point = {"altitude": float(row['altitude']),
                         "longitude": float(row['gpsLon']),
                         "latitude": float(row['gpsLat']),
                         "direction": float(row['bearing']),
                         "speed": float(row['speed']),
                         "occurred_time": datetime.strptime(row['locationTime'], "%Y-%m-%d %H:%M:%S")
                         }
            gps_points.append(gps_point)
            cnt += 1
            if cnt > 100:
                self.logger.warning(f'{set_on_insert} 数据太长')
                break

        collection_name = self._get_collection_name(start_time)
        try:
            self.db[collection_name].update_one(
                {'start_timespan': start_time, 'device_imei': vehicle_info['imei']},
                {
                    '$setOnInsert': set_on_insert,
                    '$inc': {'gps_count': len(gps_points)},
                    '$push': {'gps': {'$each': gps_points}}
                },
                upsert=True,
            )
        except Exception as e:
            print(e)
